package cn.com.fone.modules.api.common.split.strategy;

import cn.com.fone.modules.api.common.split.ContextHelpers;
import cn.com.fone.modules.api.common.split.enums.SplitTableEnum;
import cn.com.fone.modules.api.common.split.strategy.impl.HashStrategy;
import cn.com.fone.modules.api.common.split.strategy.impl.DateStrategy;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;


@Configuration
public class StrategyManager {
    private Log log = LogFactory.getLog(StrategyManager.class);
    public Map<String, Strategy> strategies = new ConcurrentHashMap<String, Strategy>(10);


    public Strategy getStrategy(String key) {
        return strategies.get(key);
    }

    public Map<String, Strategy> getStrategies() {
        return strategies;
    }

    public void setStrategies(Map<String, Strategy> strategies) {
        for (Entry<String, Strategy> entry : strategies.entrySet()) {
            try {
                this.strategies.put(entry.getKey(), (Strategy) entry.getValue());
            } catch (Exception e) {
                log.error("实例化策略出错", e);
            }
        }
        printDebugInfo();
    }

    private void printDebugInfo() {
        StringBuffer msg = new StringBuffer("初始化了" + strategies.size() + "策略");
        for (String key : strategies.keySet()) {
            msg.append("\n");
            msg.append(key);
            msg.append("  --->  ");
            msg.append(strategies.get(key));
        }
        log.debug(msg.toString());
    }

    /**
     * 初始化策略
     */
    public void initStrategy() {
        Map<String, Strategy> strategies = new HashMap<String, Strategy>();
        log.info("Initializing strategy ...");
        strategies.put(SplitTableEnum.YYYY.getValue(), ContextHelpers.getBean(DateStrategy.class));
        strategies.put(SplitTableEnum.HASH.getValue(), ContextHelpers.getBean(HashStrategy.class));
        setStrategies(strategies);
    }
}
